﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalcEngine
{
    public class LuaCodeBuilder : CodeBuilder
    {
        public LuaCodeBuilder(string variableName, StringBuilder stringBuilder)
            : base(stringBuilder)
        {
            VariableName = variableName;
        }
        public string NewLine { get { return "\n"; } }
        protected override void StartWriteCode()
        {
            base.StartWriteCode();
            Write("local " + VariableName + NewLine);
        }
        internal override void Write(FunctionDefinition functionDefinition, List<ICodeBuilder> list)
        {
            switch (functionDefinition.Function.Method.Name.ToUpper())
            {
                case "NODE":
                case "QUALITY":
                case "TRUE":
                case "FALSE":
                    Write(functionDefinition.Function.Method.Name.ToLower() + NewLine);
                    break;
                default:
                    base.Write(functionDefinition, list);
                    break;
            }
        }
        private bool WriteIfExpression(ICodeBuilder expression)
        {
            FunctionExpression functionExpression = expression as FunctionExpression;
            if (functionExpression != null)
            {
                if (new string[] { "true", "false" }.Contains(functionExpression._fn.Function.Method.Name.ToLower()))
                {
                    Write("    " + VariableName + " = ");
                }
                Write(functionExpression._fn, functionExpression._parms.Cast<ICodeBuilder>().ToList());
            }
            else
            {
                Write("    " + VariableName + " = " + expression.ToCodeString() + NewLine);
            }
            return true;
        }
        public string VariableName { get; private set; }
        protected override void WriteIf(List<ICodeBuilder> list)
        {
            Write("if " + list[0].ToCodeString() + " then" + NewLine);
            WriteIfExpression(list[1]);
            if (list.Count == 3)
            {
                Write("else" + NewLine);
                WriteIfExpression(list[2]);
            }
            Write("end" + NewLine);
        }
        internal override void EndWrite()
        {
        }

    }
}
